import traceback

import requestNovelsLib
import sys
import os

__findSubStr = "小说名称:"
__findSubStrLen = len(__findSubStr)


def getFileNovelsNameList(path: str) -> list[str]:
	"""
	读取路径文件，并且返回读取到的文件小说名称
	:param path: 文件路径
	:return: 小说名称列表
	"""
	global __findSubStr, __findSubStrLen
	result: list[str] = []
	try:
		fileContent = requestNovelsLib.readFile(path)
		contList: list[str] = fileContent.split("\n")
		findIndex = -1
		item = ""
		exis = ""
		for item in contList:
			findIndex = item.find(__findSubStr)
			if findIndex != -1:
				item = item[findIndex + __findSubStrLen:].strip()
				result.append(item)
		
		result = requestNovelsLib.strListreduce(result)
	except:
		msg = traceback.format_exc()
		sys.stderr.write(f"{msg}")
	
	return result


def getDirNovelsNameList(path: str) -> list[str]:
	"""
	读取路径文件夹，并且返回读取到的文件小说名称
	:param path: 文件夹路径
	:return: 小说名称列表
	:return: 小说名称
	"""
	result: list[str] = []
	resultList: list[str] = []
	resultItem = ""
	filePath = ""
	item = ""
	findIndex = -1
	resultLen = 0
	resultOldLen = 0
	for root, dirs, files in os.walk(path, topdown=False):
		for name in files:
			filePath = os.path.join(root, name)
			print(f"分析 {filePath}")
			resultList = getFileNovelsNameList(filePath)
			resultLen = len(resultList)
			print(f"得到 {resultLen} :{filePath} ")
			if resultLen != 0:
				for item in resultList:
					result.append(item)
		for name in dirs:
			filePath = os.path.join(root, name)
			getDirNovelsNameList(filePath)
	return result


if __name__ == '__main__':
	argvDict = requestNovelsLib.initParamArgs()
	inputPathArg = argvDict.get("i")
	## 是否存在参数
	if not inputPathArg:
		sys.stderr.write("没有获取到匹配的路径，请使用 -i 指定路径（文件/文件夹）")
		exit(-1)
	names: list[str] = []
	buff: list[str] = []
	for inputPath in inputPathArg:
		## 是否存在路径
		if not os.path.exists(inputPath):
			sys.stderr.write(f"{inputPath} 路径异常，没有获取到存在的路径信息，请使用 -i 指定路径（文件/文件夹）")
			exit(-2)
		## 获取所有名称
		if os.path.isfile(inputPath):  ## 如果是文件
			buff = getFileNovelsNameList(inputPath)
			for appenItem in buff:
				names.append(buff)
		else:  ## 如果是文件夹
			buff = getDirNovelsNameList(inputPath)
			for appenItem in buff:
				names.append(appenItem)
		buff.clear()
	names = requestNovelsLib.strListreduce(names)
	outPathDir = argvDict.get("o")
	outPath = ""
	if outPathDir is None:
		outPath = f"{requestNovelsLib.getCallAbsDirPath()}{os.sep}out{os.sep}ini{os.sep}{requestNovelsLib.getBaseFileName(__file__)}{os.sep}outKey.txt"
	else:
		outPath = outPathDir[0]
	writeContent = "\n".join(names) + "\n"
	requestNovelsLib.writeFile(writeContent, outPath)
